clear all
close all
clc
%% 参数设置
Fs = 245.76e6;        % 采样率
duration = 0.01;       % 10毫秒
f_tone = 10e6;         % 单音频率
N = round(Fs * duration);
scale = 32767;         % int16最大值
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %% 直接生成int16信号
% t = (0:N-1)'/Fs;
% signal = exp(1j*2*pi*f_tone*t); % 直接生成复数信号
% figure;plot(real(signal))
% 
% % 分离IQ并量化
% I = int16(real(signal) * scale);
% Q = int16(imag(signal) * scale);
% 
% %% 十六进制保存（无循环）
% fid = fopen('iq_data.txt','w');
% fprintf(fid, '%04X%04X\n', [typecast(I,'uint16')'; typecast(Q,'uint16')']); % 向量化写入
% fclose(fid);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% 读取数据
data = textread('output_data_d.txt','%4s'); % 自动分割所有数据
hex_pairs = reshape(data,2,[])';     % 重组为[N×2]矩阵

%% 直接转换回int16
I = typecast(uint16(hex2dec(hex_pairs(:,2))), 'int16');
Q = typecast(uint16(hex2dec(hex_pairs(:,1))), 'int16');
signal = (double(I) + 1j*double(Q))/32767; % 合并为复数信号
figure;plot(real(signal))
%%%%%%
figure; clf;
nfft = Fs/(30*1e3);
spectrogram(signal(:,1),ones(nfft,1),0,nfft,'centered',Fs,'yaxis','MinThreshold',-110);
title('Spectrogram of the Received Waveform')
%%%%%%%
%% 快速频谱分析
N = length(signal);
f_axis = (-Fs/2:Fs/N:Fs/2-Fs/N)/1e6; % MHz单位

figure;
plot(f_axis, 20*log10(fftshift(abs(fft(signal))/N)));
xlim([-100 100]); 
xlabel('Frequency (MHz)'); 
ylabel('Magnitude (dB)');
grid on;